package agenceVoyageVirtuel.server.base;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import agenceVoyageVirtuel.client.beans.SexeData;
import agenceVoyageVirtuel.server.DB_Conn;

public class DB_Sexe extends DB_Conn {
	/**
	 * constructor - nothing to do
	 */
	public DB_Sexe() {
		// nothing to do
	}
	
	public List<SexeData> getSexes() {
		String query = "SELECT idSexe, libSexe FROM t_sexe;";

		// prepare for rpc transport
		List<SexeData> sexeDatas = new ArrayList<SexeData>();
		
		try {
			Connection connection = getConn();
			Statement select = connection.createStatement();
			ResultSet result = select.executeQuery(query);
			int i = 0;
			
			while (result.next()) {
				sexeDatas.add(new SexeData());
				sexeDatas.get(i).setIdSexe(result.getInt(1));
				sexeDatas.get(i).setLibSexe(result.getString(2));
				
				i++;
			}

			// clean up
			result.close();
			connection.close();
		} catch(Exception e) {
			System.err.println("Mysql Statement Error: " + query);
			e.printStackTrace();
		}

		// return datas
		return sexeDatas;		
	}
	
	private int chercherSexe(String nouveauSexe) {
		String query = "SELECT idSexe"
				+ " FROM t_sexe"
				+ " WHERE libSexe=" + nouveauSexe
				+ ";";
	
		// prepare for rpc transport
		int id = -1;
		
		try {
			Connection connection = getConn();
			Statement select = connection.createStatement();
			ResultSet result = select.executeQuery(query);
			
			while(result.next()) {
				id = result.getInt(1); //idSexe
				break;
			}
	
			// clean up
			result.close();
			connection.close();
		} catch(Exception e) {
			System.err.println("Mysql Statement Error: " + query);
			e.printStackTrace();
		}
	
		// return datas
		return id;		
	}
	
	public void creerSexe(String nouveauSexe) {
		int id = chercherSexe(nouveauSexe);
		
		if(id != -1)
			return;
		
		String query = "INSERT INTO t_sexe (libSexe)"
				+ " VALUES (" + nouveauSexe
				+ ");";
	
		try {
			Connection connection = getConn();
			Statement  insert = connection.createStatement();
			insert.executeUpdate(query);
			
	        insert.close();
			connection.close();
		} catch(Exception e) {
			System.err.println("Mysql PrepareStatement Error: " + query);
			e.printStackTrace();
		}
		
		return;		
	}		
}
